import React, { Component } from 'react';
import {
  Tabs,
  Skeleton,
  Modal,
  Form,
  message,
  TimePicker,
  Input,
  Row,
  Col,
  Button,
  Spin
} from 'antd';
import { connect } from 'dva';

import moment from 'moment'
import get from 'lodash/get';
import router from 'umi/router';
import api from '@/api';

import StandardTable from '@/components/StandardTable';
import ScrollSelect from '@/components/ScrollSelect';
import IconButton from '@/components/IconButton';
import Import from './Import'
import styles from './ServiceView.less'

const FormItem = Form.Item
const { TabPane } = Tabs;

@Form.create()
@connect(({ base, product, loading }) => ({
  cargoTypes: base.cargoTypes,
  currentProduct: product.currentProduct,
  loading: loading.effects['product/queryServices'],
  loadingMainline: loading.effects['product/queryMainlines'],
  loadingWarehouse: loading.effects['product/queryFlight'],
}))
class ServiceView extends Component {
  state = {
    serviceList: {
      list: [],
      pagination: {}
    },
    service: {},
    detailVisible: false,
    routeGroup: [],
    nodeId: '',
    phaseId: '',
    serviceType: '',
    addServiceVisible: false,
    weightVisible: false,
    editWarehouseVisible: false,
    warehouse: {
      list: [],
      pagination: {}
    },
    flightNo: '',
    supplierId: '',
    editWarehouse: {},
    importVisible: false,
    file: {},
    filePath: '',
    importResult: [],
    selectedRows: []
  }
  columns = [
    {
      title: '序号',
      render: (text, record, index) => {
        return <span>{this.calcIndex(index)}</span>;
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      render: (text, record) => {
        return <a onClick={this.handleDetail.bind(this, record)}>{text}</a>
      }
    },
    {
      title: '编码',
      dataIndex: 'code'
    },
    {
      title: '供应商',
      dataIndex: 'supplierName'
    },
  ]
  warehouseColumns = [
    {
      title: '班期',
      dataIndex: 'flightDate',
      render: (text, record) => {
        return (
          <a onClick={this.handleEditWarehouse.bind(this, record)}>{text}</a>
        )
      }
    },
    {
      title: '计划起飞时间',
      dataIndex: 'startTime'
    },
    {
      title: '计划到达时间',
      dataIndex: 'arriveTime'
    },
    {
      title: '剩余舱位',
      dataIndex: 'weight'
    },
    {
      title: '锁定舱位',
      dataIndex: 'lockWeight'
    },
    {
      title: '已用舱位',
      dataIndex: 'usedWeight'
    }
  ]
  calcIndex = index => {
    const { serviceList } = this.state;
    let currentPage = get(serviceList, 'pagination.currentPage') || 1;
    let pageSize = get(serviceList, 'pagination.pageSize') || 50;
    return (currentPage - 1) * pageSize + index + 1;
  };
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'base/fetchServiceTypes' });
    dispatch({ type: 'base/fetchCargoTypes' });
    dispatch({ type: 'base/fetchRating' });
    this.searchRoutesGroup();
  }
  handleCheckWeight = (record) => {
    this.setState({ flightNo: record.flightNo, supplierId: record.supplierId })
    this.queryWarehouse({ flightNo: record.flightNo, supplierId: record.supplierId })

  }
  queryWarehouse = ({ pageIndex = 1, pageSize = 50, ...rest } = {}) => {
    const { dispatch, location } = this.props;
    const { flightNo, supplierId } = this.state;
    const isTime = location.pathname.includes('time')
    dispatch({
      type: 'product/queryFlight',
      payload: {
        queryParams: {
          pageIndex,
          pageSize,
          flightNo: flightNo || rest.flightNo,
          supplierId: supplierId || rest.supplierId,
          channel: isTime ? 2 : 1
        }
      }
    }).then(({ errorCode, data, pagination }) => {
      if (errorCode === 0) {
        this.setState({ warehouse: { list: data, pagination }, weightVisible: true })
      }
    })
  }
  handleWarehouseTableChange = (pagination) => {
    let params = { pageIndex: pagination.current, pageSize: pagination.pageSize }
    this.queryWarehouse(params)
  }
  handleWeightCancel = () => {
    this.setState({ weightVisible: false, flightNo: '' })
  }
  // 查询服务环节
  searchRoutesGroup = () => {
    const { dispatch, currentProduct } = this.props;
    dispatch({
      type: 'product/fetchRoutesGroup',
      payload: {
        queryParams: {
          productId: currentProduct.id,
        },
      },
    }).then(({ errorCode, data }) => {
      if (errorCode === 0) {
        this.setState({ routeGroup: data || [] })
        if (data.length !== 0) {
          this.setState({ nodeId: data[0].nodeDtoExList[0].id, phaseId: data[0].nodeDtoExList[0].phaseId, serviceType: data[0].nodeDtoExList[0].serviceTypeCode })
          this.queryService({ nodeId: data[0].nodeDtoExList[0].id })
        }
      }
    });
  };
  queryService = ({ pageSize = 50, pageIndex = 1, serviceType = 'ST001', ...rest } = {}) => {
    const { dispatch, location, form: { validateFields } } = this.props;
    let productType = location.pathname.split('/')[2]
    let id;
    switch (productType) {
      case 'today':
        id = 10000
        break;
      case 'tomorrow':
        id = 10001
        break;
      case 'time':
        id = 10002
        break
      default:
        id = 10000
    }
    validateFields(['serviceName', 'supplierId'], (err, value) => {
      let searchParams = {}
      if (value.serviceName) {
        searchParams.serviceName = value.serviceName.trim()
      }
      if (value.supplierId) {
        searchParams.supplierId = value.supplierId.key
      }
      dispatch({
        type: serviceType === 'ST004' ? 'product/queryMainlines' : 'product/queryServices',
        payload: {
          queryParams: {
            pageSize,
            pageIndex,
            productId: id,
            ...rest,
            ...searchParams
          }
        }
      }).then(({ errorCode, data, pagination }) => {
        if (errorCode === 0) {
          this.setState({ serviceList: { list: data, pagination } })
        }
      })
    })
  }
  handleTabChange = (value) => {
    const { form } = this.props;
    let list = value.split('-')
    this.setState({ nodeId: list[0], phaseId: list[1], serviceType: list[2], selectedRows: [], })
    form.resetFields(['supplierId', 'serviceName'])
    this.queryService({ nodeId: list[0], serviceType: list[2] })

  }
  handleTableChange = (pagination) => {
    const { nodeId, serviceType } = this.state;
    let params = { pageIndex: pagination.current, pageSize: pagination.pageSize, nodeId, serviceType }
    this.queryService(params)
  }

  // 点击名称查看详情
  handleDetail = (record) => {
    const { location } = this.props;
    const { nodeId, phaseId, serviceType } = this.state;
    router.push(`/product/${location.pathname.split('/')[2]}/service/base?serviceId=${record.id}&serviceType=${serviceType}&nodeId=${nodeId}&phaseId=${phaseId}&backRoute=${location.pathname}`)
  }
  handleAddNewService = () => {
    const { location } = this.props;
    const { nodeId, phaseId, serviceType } = this.state;
    if (serviceType === 'ST004') {
      router.push(`/product/${location.pathname.split('/')[2]}/air?serviceType=${serviceType}&nodeId=${nodeId}&phaseId=${phaseId}&backRoute=${location.pathname}`)
    } else {
      router.push(`/product/${location.pathname.split('/')[2]}/service/base?serviceType=${serviceType}&nodeId=${nodeId}&phaseId=${phaseId}&backRoute=${location.pathname}`)
    }
  }
  handleAdd = () => {
    this.setState({ addServiceVisible: true })
  }
  searchService = params => {
    const { serviceType } = this.state;
    return api.service.queryOnline({
      queryParams: {
        serviceTypeCode: serviceType,
        ...params,
      },
    });
  };
  handleAddService = () => {
    const { dispatch, form: { validateFields } } = this.props;
    const { nodeId, serviceType } = this.state;
    validateFields(['serviceId'], (err, value) => {
      if (err) return
      dispatch({
        type: 'product/addService',
        payload: {
          pathParams: {
            nodeId,
          },
          data: {
            serviceId: value.serviceId.key
          },
        },
      }).then(({ errorCode }) => {
        if (errorCode === 0) {
          message.success('添加成功');
          this.handleCancelAddService()
          this.queryService({ nodeId, serviceType })
        }
      });
    })
  }
  handleCancelAddService = () => {
    const { form: { resetFields } } = this.props;
    resetFields(['serviceId'])
    this.setState({ addServiceVisible: false })
  }
  handleEditWarehouse = (value) => {
    const { form: { setFieldsValue } } = this.props;
    this.setState({ editWarehouse: value, editWarehouseVisible: true })
    setFieldsValue({ startTime: moment(value.startTime, 'HH:mm'), arriveTime: moment(value.arriveTime, 'HH:mm'), weight: value.weight })
  }
  handleSubmitWarehouse = () => {
    const { form: { validateFields }, dispatch } = this.props;
    const { editWarehouse } = this.state;
    validateFields(['startTime', 'arriveTime', 'weight'], (err, value) => {
      if (err) return
      dispatch({
        type: 'product/putFlight',
        payload: {
          data: {
            id: editWarehouse.id,
            startTime: moment(value.startTime).format('HH:mm'),
            arriveTime: moment(value.arriveTime).format('HH:mm'),
            weight: value.weight
          }
        }
      }).then(({ errorCode, data }) => {
        if (errorCode === 0) {
          this.queryWarehouse()
          message.success('修改舱位量成功')
          this.setState({ editWarehouseVisible: false, editWarehouse: {} })
        }
      })
    })
  }
  handleCancelWarehouse = () => {
    this.setState({ editWarehouse: {}, editWarehouseVisible: false })
  }
  handleImport = () => {
    this.setState({ importVisible: true })
  }
  handleImportCancel = () => {
    this.setState({ importVisible: false })
  }
  handleImportSuccess = () => {
    const { serviceType, nodeId } = this.state;
    this.handleImportCancel()
    this.queryService({ nodeId, serviceType })

  }
  handleEditAirService = (value) => {
    const { location } = this.props;
    const { nodeId, phaseId, serviceType } = this.state;
    router.push(`/product/${location.pathname.split('/')[2]}/air?serviceId=${value.id}&serviceType=${serviceType}&nodeId=${nodeId}&phaseId=${phaseId}&backRoute=${location.pathname}`)
  }
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  handleDelete = () => {
    const { dispatch, deleteLoading } = this.props;
    if (deleteLoading) return
    const { selectedRows, serviceType, nodeId } = this.state;
    Modal.confirm({
      title: '删除服务',
      content: '确定删除已选服务吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        const serviceId = serviceType === "ST004" ? selectedRows[0].serviceId : selectedRows[0].id;
        return dispatch({
          type: 'product/deleteService',
          payload: {
            pathParams: {
              nodeId: nodeId,
              serviceId: serviceId,
            },
          },
        }).then(res => {
          if (res.errorCode === 0) {
            message.success('删除成功');
            this.queryService({ nodeId, serviceType })
            this.setState({
              selectedRows: [],
            });
          }
        });
      },
    });
  }
  range = (start, end) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  }
  disableStartHour = () => {
    const { form: { getFieldValue } } = this.props;
    let time = getFieldValue('arriveTime')
    if (!time) return []
    return this.range(+moment(time).format('HH') + 1, 24)
  }
  disableArriveHour = () => {
    const { form: { getFieldValue } } = this.props;
    let time = getFieldValue('startTime')
    if (!time) return []
    return this.range(0, +moment(time).format('HH'))
  }
  disableStartMinute = (hour) => {
    const { form: { getFieldValue } } = this.props;
    let time = getFieldValue('arriveTime')
    if (time === undefined) {
      return []
    }
    let arriveHour = moment(time).format('HH')
    if (hour < arriveHour) {
      return []
    }
    return this.range(+moment(time).format('mm'), 59)
  }
  disableArriveMinute = (hour) => {
    const { form: { getFieldValue } } = this.props;
    let time = getFieldValue('startTime')
    if (time === undefined) {
      return []
    }
    let startHour = moment(time).format('HH')
    let startMinute = moment(time).format('mm')
    if (hour > startHour) {
      return []
    }
    return this.range(0, +startMinute + 1)
  }
  handleReset = () => {
    const { form } = this.props;
    const { serviceType, nodeId } = this.state
    form.resetFields(['supplierId', 'serviceName'])
    this.queryService({ serviceType, nodeId })
  }
  querySuppliers = params => {
    return api.supplier.shortQuery({
      queryParams: params,
    });
  };
  render() {
    const { serviceList, routeGroup, addServiceVisible, serviceType, selectedRows, weightVisible, warehouse, editWarehouseVisible, editWarehouse, importVisible, nodeId, phaseId } = this.state;
    const { currentProduct, loading, form: { getFieldDecorator }, loadingMainline, loadingWarehouse, location } = this.props;
    const productType = location.pathname.split('/')[2]
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };
    let serviceColumns = [
      {
        title: '序号',
        render: (text, record, index) => {
          return <span>{this.calcIndex(index)}</span>;
        },
      },
      {
        title: '适用航线',
        render: (text, record) => {
          return <a onClick={this.handleEditAirService.bind(this, record)}>{record.startPlaceName}-{record.endPlaceName}</a>
        }
      },
      {
        title: '航班号',
        dataIndex: 'flightNo',

      },
      {
        title: '投放腹舱量(kg)',
        render: (text, record) => {
          return <a onClick={this.handleCheckWeight.bind(this, record)}>查看</a>
        }
      },
      {
        title: '货物类型',
        dataIndex: 'cargoTypeNameList'
      },
      {
        title: '资源提供方',
        dataIndex: 'supplierName'
      },
    ]
    if (productType === 'time') {
      serviceColumns = [
        {
          title: '序号',
          render: (text, record, index) => {
            return <span>{this.calcIndex(index)}</span>;
          },
        },
        {
          title: '适用航线',
          render: (text, record) => {
            return <a onClick={this.handleEditAirService.bind(this, record)}>{record.startPlaceName}-{record.endPlaceName}</a>

          }
        },
        {
          title: '航班号',
          dataIndex: 'flightNo',

        },
        {
          title: '投放腹舱量(kg)',
          render: (text, record) => {
            return <a onClick={this.handleCheckWeight.bind(this, record)}>查看</a>
          }
        },
        {
          title: '货物类型',
          dataIndex: 'cargoTypeNameList'
        },
        {
          title: '成本单价(元/kg)',
          dataIndex: 'costUnitPrice'
        },
        {
          title: '销售单价(元/kg)',
          dataIndex: 'saleUnitPrice'
        },
        {
          title: '起订量(kg)',
          dataIndex: 'startWeight'
        },
        {
          title: '收货时效要求(小时)',
          dataIndex: 'hours'
        },
        {
          title: '资源提供方',
          dataIndex: 'supplierName'
        },
        {
          title: '服务商',
          dataIndex: "operateSupplierName"
        },
        {
          title: '收货地址',
          dataIndex: 'address'
        },
        {
          title: '联系电话',
          dataIndex: 'mobile'
        }
      ]
    }

    const canModify = currentProduct && !currentProduct.isOnline || false;
    return (
      <div>
        <Spin spinning={!!(loading || loadingMainline)}>
          {
            routeGroup.length === 0 &&
            < Skeleton active />
          }
          {
            routeGroup.length !== 0 &&
            <Tabs onChange={this.handleTabChange}>
              {
                routeGroup.map(item => (
                  <TabPane tab={item.nodeDtoExList[0].nodeName} key={`${item.nodeDtoExList[0].id}-${item.nodeDtoExList[0].phaseId}-${item.nodeDtoExList[0].serviceTypeCode}`}>

                  </TabPane>
                ))
              }
            </Tabs>
          }
          <div style={{ marginBottom: 20 }}>
            {
              productType !== 'time' &&
              <div className={styles.search}>
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                  {
                    serviceType !== 'ST004' &&
                    <Col md={8} sm={24}>
                      <FormItem label="名&emsp;称" {...formItemLayout}>
                        {getFieldDecorator('serviceName')(
                          <Input maxLength={20} style={{ width: '100%' }}></Input>
                        )}
                      </FormItem>
                    </Col>
                  }
                  {
                    serviceType === 'ST004' &&
                    <Col md={8} sm={24}>
                      <FormItem label="航班号" {...formItemLayout}>
                        {getFieldDecorator('serviceName')(
                          <Input maxLength={20} style={{ width: '100%' }}></Input>
                        )}
                      </FormItem>
                    </Col>
                  }
                  <Col md={8} sm={24}>
                    <FormItem label="供应商" {...formItemLayout}>
                      {getFieldDecorator('supplierId')(
                        <ScrollSelect
                          style={{ width: '100%' }}
                          search={this.querySuppliers}
                          optionKey="id"
                          filterOption={false}
                          allowClear
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <Button onClick={this.handleReset}>重置</Button>
                    <Button type='primary' onClick={this.queryService.bind(this, { nodeId, serviceType })}>查询</Button>
                  </Col>
                </Row>
              </div>
            }
            {
              canModify && serviceType !== 'ST004' &&
              <IconButton icon='icon-add' title='添加' onClick={this.handleAdd}></IconButton>
            }
            {
              canModify && serviceType === 'ST004' &&
              <IconButton
                title="导入"
                icon="icon-import"
                style={{ marginLeft: 10 }}
                onClick={this.handleImport}
              ></IconButton>
            }
            {canModify && selectedRows.length === 1 &&
              < IconButton
                title="删除"
                icon="icon-delete"
                style={{ marginLeft: 10 }}
                onClick={this.handleDelete}
              ></IconButton>
            }
          </div>
          <StandardTable
            showCheckbox={canModify}
            selectedRows={selectedRows}
            data={serviceList}
            columns={serviceType === 'ST004' ? serviceColumns : this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleTableChange}
          />
          <Modal
            title='添加服务'
            keyboard={false}
            visible={addServiceVisible}
            onOk={this.handleAddService}
            onCancel={this.handleCancelAddService}
            bodyStyle={{ position: 'relative' }}
          >
            <FormItem label="服务名称" labelCol={{ span: 5 }} wrapperCol={{ span: 17 }}>
              {getFieldDecorator('serviceId', {
                rules: [{ required: true, message: '服务名称不能为空' }],
              })(
                <ScrollSelect
                  style={{ width: 300 }}
                  search={this.searchService}
                  optionKey="id"
                  filterOption={false}
                />
              )}
            </FormItem>
            <div style={{ position: 'absolute', top: 28, right: 56 }}>
              <IconButton icon='icon-add' title='添加服务' onClick={this.handleAddNewService}></IconButton>
            </div>
          </Modal>
          <Modal
            keyboard={false}
            title='腹舱量'
            width={700}
            visible={weightVisible}
            onOk={this.handleWeightCancel}
            onCancel={this.handleWeightCancel}
          >
            <StandardTable
              loading={loadingWarehouse}
              data={warehouse}
              columns={this.warehouseColumns}
              onChange={this.handleWarehouseTableChange}
            />
          </Modal>
          <Modal
            keyboard={false}
            title='编辑腹舱量'
            width={700}
            visible={editWarehouseVisible}
            onOk={this.handleSubmitWarehouse}
            onCancel={this.handleCancelWarehouse}
          >

            <FormItem label="计划起飞时间" {...formItemLayout}>
              {getFieldDecorator('startTime', {
                rules: [
                  {
                    required: true, message: '请选择计划起飞时间'
                  }
                ],
                initialValue: moment(editWarehouse.startTime, 'HH:mm')
              })(
                <TimePicker format='HH:mm' disabledHours={this.disableStartHour} disabledMinutes={this.disableStartMinute} />
              )}
            </FormItem>
            <FormItem label="计划到达时间" {...formItemLayout}>
              {getFieldDecorator('arriveTime', {
                rules: [
                  {
                    required: true, message: '请选择计划到达时间'
                  }
                ],
                initialValue: moment(editWarehouse.arriveTime, 'HH:mm')
              })(
                <TimePicker format='HH:mm' disabledHours={this.disableArriveHour} disabledMinutes={this.disableArriveMinute} />
              )}
            </FormItem>
            <FormItem label="舱位量" {...formItemLayout}>
              {getFieldDecorator('weight', {
                rules: [
                  {
                    required: true, message: '请输入舱位量'
                  }
                ],
                initialValue: editWarehouse.weight
              })(
                <Input maxLength={6} minLength={5} style={{ width: 380 }}></Input>
              )}
            </FormItem>
          </Modal>
          <Modal
            keyboard={false}
            title='导入'
            width={700}
            visible={importVisible}
            footer={null}
            onCancel={this.handleImportCancel}
          >
            <Import productType={productType} nodeId={nodeId} phaseId={phaseId} onChange={this.handleImportSuccess} visible={importVisible}></Import>
          </Modal>
        </Spin>
      </div>
    )
  }
}

export default ServiceView
